namespace Billing2
{
    using Billing2.Controls;
    using System;
    using System.Data;
    using System.Text.RegularExpressions;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using MyLib;

    public class ChangePassword : Page
    {
        protected Button BtnSave;
        protected Label lblUserName;
        protected TextBox txtConfirmNewPassword;
        protected TextBox txtNewPassword;
        protected TextBox txtOldPassword;
        protected ucHighlight ucHighlight1;
        protected ucPageTitle ucPageTitle1;
        protected UpdatePanel UpdatePanel4;
        protected UpdateProgress UpdateProgress1;

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                int? times = Common.db.SelectInt(@"
                    select count(*)
                    from PasswordHistory
                    where LoginId = @LoginId
                        and Action = @Action
                        and CreatedAt > dateadd(day, -1, getdate())
                    ", LoginUser.LoginID
                     , LoginUser.UserAction_ChangePassword);
                if (times >= ClsApplicationConfiguration.ChangePasswordTimesPerDay)
                    throw new Prompt("Password can only be changed " + ClsApplicationConfiguration.ChangePasswordTimesPerDay.ToString() + " times per day");
                
                if (this.txtOldPassword.Text.Trim() == "")
                    throw new Prompt("Invalid old password");
                if (this.txtNewPassword.Text.Trim() != this.txtConfirmNewPassword.Text.Trim())
                    throw new Prompt("New password not match");
                if (this.txtOldPassword.Text.Trim() == this.txtNewPassword.Text.Trim())
                    throw new Prompt("Old Password same as new password ");

                ClsUserProfile cls = new ClsUserProfile
                {
                    LoginId = LoginUser.LoginID,
                    LoginPassword = ClsUserProfile.EncryptPwd(this.txtOldPassword.Text)
                };
                DataTable dt = cls.DoLogin();
                if (dt == null)
                    throw new Prompt("Invalid Old Password");
                if (dt.Rows.Count == 0)
                    throw new Prompt("Invalid Old Password");
                if (this.txtNewPassword.Text.Trim() == "")
                    throw new Prompt("Invalid new password, password cannot empty");
                if (this.txtNewPassword.Text.Trim() != this.txtConfirmNewPassword.Text.Trim())
                    throw new Prompt("Invalid new password");

                Regex match = new Regex(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$");
                if (!match.IsMatch(this.txtNewPassword.Text))
                    throw new Prompt("Passwords must be at least eight (8) characters in length and contain both letters (uppercase and lowercase) and numbers");

                match = new Regex(".*[a-z].*");
                if (!match.IsMatch(this.txtNewPassword.Text))
                    throw new Prompt("Password must contain a-z");

                match = new Regex(".*[A-Z].*");
                if (!match.IsMatch(this.txtNewPassword.Text))
                    throw new Prompt("Password must contain A-Z");

                match = new Regex(".*[0-9].*");
                if (!match.IsMatch(this.txtNewPassword.Text))
                    throw new Prompt("Password must contain 0-9");

                if (Global.IsCommonPW(this.txtNewPassword.Text))
                    throw new Prompt("This is a well-known password! Please use another secure password.");

                cls.LoginPassword = ClsPasswordHelper.Encrypt(this.txtNewPassword.Text);

                times = Common.db.SelectInt(@"
                    select count(*)
                    from PasswordHistory
                    where LoginId = @LoginId
                        and LoginPassword = @LoginPassword
                        and CreatedAt > dateadd(day, -@days, getdate())
                    ", LoginUser.LoginID
                     , cls.LoginPassword
                     , ClsApplicationConfiguration.ChangePasswordMinimumAgeDays);
                if (times > 0)
                    throw new Prompt("Can not use previous password in " + ClsApplicationConfiguration.ChangePasswordMinimumAgeDays.ToString() + " days");

                Common.db.Exec(@"
                    insert into PasswordHistory(LoginId, LoginPassword, Action)
                    values(@LoginId, @LoginPassword, @Action)
                    ", LoginUser.LoginID
                     , cls.LoginPassword
                     , LoginUser.UserAction_ChangePassword);

                cls.UpdateByLoginIdForPassword();

                this.ucHighlight1.Message = "Password successfully updated";
                this.BtnSave.Visible = false;
            }
            catch (Exception ex)
            {
                if (ex is Prompt)
                    this.ucHighlight1.ErrorMessage = ex.Message;
                else
                {
                    EPPLog.Logger.Error(ex);
                    this.ucHighlight1.ErrorMessage = "Internal error";
                }
            }
        }

        private void GetPermission()
        {
            ClsACLHelper cls = new ClsACLHelper();
            string pageName = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx";
            cls.SetPermission(LoginUser.TreeMenu, pageName);
            if (!cls.Read0)
            {
                base.Response.Redirect("logout.aspx", true);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Session["SiteID"] == null)
            {
                base.Response.Redirect("default.aspx", true);
            }
            this.lblUserName.Text = Microsoft.Security.Application.Encoder.HtmlEncode(LoginUser.LoginID);
            this.GetPermission();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ViewStateUserKey = Session.SessionID;
        }
    }
}
